package com.prashantdctm.utils;

import java.io.IOException;
import java.net.URL;

import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.html.HTMLParserListener;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.prashantdctm.paidemail.GaeWebClient;

public class HttpUtil {
	private static final Logger log = Logger.getLogger(HttpUtil.class.getName());
	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

	public static HtmlAnchor getAnchorContains(HtmlPage page, String anchorStr) {
		for (HtmlAnchor anchor : page.getAnchors()) {
			if (anchor.getHrefAttribute().contains(anchorStr)) {
				return anchor;
			}
		}
		return null;
	}
	
	public static HtmlAnchor getAnchorStartsWith(HtmlPage page, String anchorStr) {
		HtmlAnchor anchor = null;
		for (HtmlAnchor anchor1 : page.getAnchors()) {
			if (anchor1.getHrefAttribute().startsWith(anchorStr)) {
				anchor = anchor1; break;
			}
		}
		return anchor;
	}
	
	public static GaeWebClient getWebClient() {
		GaeWebClient webClient = null;
		try {
			webClient = new GaeWebClient(BrowserVersion.INTERNET_EXPLORER_7);
			webClient.setRefreshHandler(new RefreshHandler() {
				public void handleRefresh(Page page, URL url, int arg)
						throws IOException {
				}
			});
			webClient.setHTMLParserListener(HTMLParserListener.LOG_REPORTER);
			webClient.setPopupBlockerEnabled(false);
			webClient.setTimeout(50000); // timout in ms
			webClient.setRedirectEnabled(true); // follow redirects
			webClient.setThrowExceptionOnFailingStatusCode(false);
			webClient.setJavaScriptEnabled(true);
			webClient.setThrowExceptionOnScriptError(false);
			webClient.setUseInsecureSSL(true);
			webClient.setCssEnabled(true);
			webClient.getCookieManager().setCookiesEnabled(true);
		} catch (Exception e) {
			log.debug("error initializing webclient)");
			e.printStackTrace();
		}
		return webClient;
	}
}
